package pers.wwz.study.minio.controller;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.RemoveBucketArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import pers.wwz.study.minio.response.RestResult;

import javax.annotation.Resource;

/**
 * bucket管理
 */
@Slf4j
@RestController
@RequestMapping("/minioBucket")
public class MinioBucketController {

    @Resource
    private MinioClient minioClient;

    /**
     * 创建bucket
     * @param bucketName
     * @return ResponseData
     */
    @PostMapping("/createBucket")
    public RestResult createBucket(@RequestParam(name = "bucketName") String bucketName){
            try {
                boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName.toLowerCase()).build());
                if (!isExist) {
                    minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName.toLowerCase()).build());
                }else {
                    return RestResult.error("bucket:"+bucketName+"已经存在,不能创建");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return RestResult.success();
    }

    /**
     * 删除bucket
     * @param bucketName
     * @return
     */
    @PostMapping("/deleteBucket")
    public RestResult deleteBucket(@RequestParam(name = "bucketName") String bucketName){
        try {
            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName.toLowerCase()).build());
            if (isExist) {
                minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName.toLowerCase()).build());
            }else {
                return RestResult.error("bucket:"+bucketName+"不存在存在,不能删除");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return RestResult.error("bucket:"+bucketName+"删除错误,错误原因:"+e.getMessage());
        }
        return RestResult.success();
    }



}
